// 发布帖子
export async function addPost(PB) {
  let success = false
  if (!this.postTitle.trim() && !this.postContent.trim()) {
    alert("您必须填写标题和内容")
    return
  }
  try {
    const formData = new FormData(this.$refs.postForm)
    formData.append("content", this.postContent)
    formData.append("author", this.user.id)
    formData.append("datetime", new Date().toISOString())

    if (this.imageFiles.length > 0) {
      console.log(this.imageFiles.join(","))
      this.imageFiles.forEach((fileId) => {
        formData.append("files", fileId)
      })
    }

    const newPost = await PB.collection("posts").create(formData)

    success = true
    console.log("帖子发布成功:", newPost)
  } catch (err) {
    console.error("帖子发布失败", err)
    alert("发布失败，请稍后重试！")
  }

  // 一些重置的操作
  if (success) {
    this.resetPostForm() // 调用新的重置方法
    // 重新获取帖子列表
    await this.fetchPosts()
  }
}

// 删除帖子
export async function delPost(PB, post) {
  if (post.author !== this.user.id) {
    alert("无权删除")
    return
  }
  if (!confirm("确定要删除这条帖子吗？")) return
  try {
    await PB.collection("posts").delete(post.id)
    this.fetchPosts()
    console.log("删除成功")
  } catch (err) {
    alert("删除失败")
    console.log("删除失败", err)
  }
}

// 弹出帖子编辑框
export function editPost(post) {
  const newContent = prompt("修改帖子内容：", post.content)
  if (newContent !== null) {
    this.updatePost(post.id, newContent)
  }
}

// 更新帖子
export async function updatePost(PB, id, content) {
  try {
    await PB.collection("posts").update(id, { content })
    this.fetchPosts()
  } catch (err) {
    alert("更新失败")
    console.log("更新失败", err)
  }
}

// 获取帖子列表
export async function fetchPosts(PB) {
  try {
    const result = await PB.collection('posts').getList(this.currentPage, this.perPage, {
      expand: 'files,author', // 展开 author 字段
      sort: '-datetime', // 按时间倒序排列
    })
    console.log("帖子加载成功:", result)
    this.posts = result.items
    this.totalPages = result.totalPages
  } catch (err) {
    console.error("获取帖子失败", err)
  }
}